<?php

include("Commons.php");

loginRequired( getTerm('messaging', 'messaging') );

$action = param('ac');
$draftid = 0;
$sentflag = 0;
$userid = $_SESSION['user'];

debug('Action : '. $action);

if ( $action=='goto' )
{
	$folder = trim($_POST['toFolder']);
	
	$path = '/messaging/';
	if ( $folder!='' )
		$path .= $folder.'/';

	redirect( formatUrl($path) );
}
elseif ( $action==getTerm('messaging','delete_message') || $action==getTerm('messaging','delete_draft') )
{
	$messageid = param('mid');
	
	query("DELETE FROM message WHERE id='$messageid' AND visibleby='$userid';");

	$_SESSION['message'] = getTerm('messaging', 'message_deleted');
}

elseif ( $action==getTerm('messaging','report_message') )
{
	$messageid = param('mid');

	$rh = query("SELECT `from` FROM message WHERE id='$messageid';");
	list($sender_id) = mysql_fetch_array($rh);

	$rh = query("SELECT COUNT(DISTINCT reporter_id) FROM reports WHERE report_date > DATE_SUB(NOW(), INTERVAL 48 HOUR) AND reported_id = $sender_id");
	list($reports) = mysql_fetch_array($rh);

	if ($reports >= 2) {
		query("UPDATE `user` SET `banned`=1 WHERE `id`=$sender_id;");
		query("DELETE FROM `reports` WHERE `reported_id`=$sender_id;");
		query("DELETE FROM `message` WHERE `from`=$sender_id;");
	} else {
		query("INSERT IGNORE INTO reports (reporter_id,reported_id,message_id,report_date) VALUES ('$userid','$sender_id','$messageid', NOW());");
	}

	$_SESSION['message'] = getTerm('messaging','report_sent');

}

elseif ( $action==getTerm('messaging','delete_selected_messages') || $action==getTerm('messaging','delete_selected_drafts') )
{
	$selection = $_POST['selection'];
	
	foreach ($selection as $mid)
		if ( is_numeric($mid) )
			query("DELETE FROM message WHERE id='$mid' AND visibleby='$userid';");

	$_SESSION['message'] = getTerm('messaging', 'messages_deleted');
	
	redirect( formatUrl('/messaging/') );
}
elseif ( $action==getTerm('messaging', 'save_as_draft') )
{
	$username = param('username');
	$subject = param('subject');
	$message = param('message');

	query("INSERT INTO `message` (`from`,`toname`,`date`,`subject`,`message`,`draftflag`,`visibleby`,processed) VALUES ('$userid', '$username', NOW(), '$subject', '$message',1,'$userid',1);");

	$_SESSION['message'] = getTerm('messaging', 'message_saved');
	
	redirect( formatUrl('/messaging/') );
}
elseif ( $action==getTerm('messaging', 'save_draft') )
{
	$username = param('username');
	$subject = param('subject');
	$message = param('message');
	$draftid = param('did');

	query("	UPDATE	`message`
			SET		`toname`='$username',
					`date`=NOW(),
					`subject`='$subject',
					`message`='$message'
			WHERE	`id`='$draftid'
			AND		`visibleby`='$userid';");

	$_SESSION['message'] = getTerm('messaging', 'message_saved');
	
	redirect( formatUrl('/messaging/') );
}
elseif ( $action==getTerm('messaging', 'send_message') )
{

	$username = param('username');
	$subject = param('subject');
	$message = param('message');
	
	if ( empty($username) )
		$usernameerror = getTerm('messaging', 'no_username');
	
	elseif ( ! eregi('^[a-zA-Z0-9_]+$', $username) )
		$usernameerror = fill( getTerm('messaging', 'invalid_username') , $username );
		
	else
	{
		$rh = query("	SELECT	id,username,email
						FROM	user
						WHERE	username='$username';");
				
		if ( mysql_num_rows($rh)==0 )
			$usernameerror = fill( getTerm('messaging', 'username_doesnt_exist') , $username );
		
		else
			list($usernameid, $toname, $tomail) = mysql_fetch_array($rh);
			
		if ( $usernameid==$userid )
			$usernameerror = getTerm('messaging', 'cannot_send_to_yourself');
	}
	
		
	if ( empty($subject) )
		$subjecterror = getTerm('messaging', 'no_subject');
		
	if ( empty($message) )
		$messageerror = getTerm('messaging', 'no_message');
		
	list($left, $limit) = check_messages($userid);
	if ($left <= 0) {
		$messageerror = getTerm('messaging', 'limit_reached');
	}

	if ( !empty($usernameerror) || !empty($subjecterror) || !empty($messageerror) )
		$action = 'write';
		
	else {
		if ( hasValidProfile($userid) && !isBanned($userid)) {
			query("	INSERT INTO message
						(`from`,`to`,`toname`,`date`,`subject`,`message`,`draftflag`,`visibleby`,`processed`)
				VALUES	('$userid', '$usernameid', '$username', NOW(), '$subject', '$message',0,'$userid',0) ;");
			processUserMessages($userid);
		} else {
			$_SESSION['message'] = fill( getTerm('messaging', 'message_sent') , $username);
		}

			
		if ( array_key_exists('did', $_POST) )
		{
			$draftid = param('did');
			query("	DELETE FROM message
					WHERE id='$draftid' AND visibleby='$userid';");
		}
	
		redirect( formatUrl('/messaging/') );
	}
}
elseif ( $action=='read' )
{
    $messageid = param('message');
	
    $rh = query("   SELECT m.id as 'messageid',subject,date,message,u.username AS 'sender',u.id AS 'senderid',m.toname AS 'recipient',draftflag
                    FROM message m
                    JOIN user u ON m.from=u.id
                    WHERE m.id=$messageid
                    AND m.visibleby=$userid
                    ORDER BY date DESC;");
                    
    if ( mysql_num_rows($rh)>0 )
    {
        $message = mysql_fetch_assoc($rh);
        
        if ( $message['draftflag']==1 )
        {
            $username = $message['recipient'];
            $subject = $message['subject'];
            $draftid = $message['messageid'];
            $messageid = $message['messageid'];
            $message = $message['message'];
	
            $action = "write";
        }
        else
        {
			if ( $message['senderid']==$userid )
				$sentflag = 1;

	        $date = formatDate($message['date']);
	        $time = formatTime($message['date']);
            $messageid = $message['messageid'];
			$sender = '<a href="'. formatUrl('/profile/'. $message['sender']) .'">'. $message['sender'] .'</a>';
			$recipient = '<a href="'. formatUrl('/profile/'. $message['recipient']) .'">'. $message['recipient'] .'</a>';
			$subject = $message['subject'];
	        $message = str_replace("\n", "<br/>", $message['message']);
        }
    }
}
elseif ( $action==getTerm('messaging', 'reply_message') )
{
    $messageid = param('message');
    
    $rh = query("   SELECT subject,message,u.username AS 'sender'
                    FROM message m
                    JOIN user u ON m.from=u.id
                    WHERE m.id=$messageid
                    AND m.visibleby=$userid
                    ORDER BY date DESC;");
                    
    if ( mysql_num_rows($rh)>0 )
    {
    	$message = mysql_fetch_assoc($rh);
		redirect( formatUrl('/messaging/write/'. $message['sender']) );
    }
}

if ( $action=='read' )
{
	pushNavigationItem( getTerm('messaging', 'messaging'), '/messaging/' );
	
	if ( $sentflag==1 )
    	pushNavigationItem( getTerm('messaging', 'sent_items'), '/messaging/sent/' );
  
    pushNavigationItem( $subject, '/messaging/message-'. $messageid .'.html' );

    printHeader( getTerm('base', 'site_name') , $subject, 'messaging' );

	print "<form action=\"${_SERVER[REQUEST_URI]}\" method=\"post\">";
	
    print '<div>'. getTerm('messaging', 'from') .' : '. $sender .'</div>';
    print '<div>'. getTerm('messaging', 'to') .' : '. $recipient .'</div>';
    print '<div>'. getTerm('messaging', 'date') .' : '. $date .', '. $time .'</div>';
    print '<p>'. $message .'</p>';
    
	print '<div class="field">';
	
	if ( $sentflag==0 )
		print '<input type="submit" name="ac" value="'. getTerm('messaging', 'reply_message') .'" /> ';
	
	print '<input type="submit" name="ac" value="'. getTerm('messaging', 'delete_message') .'" />';
	print '<input type="hidden" name="mid" value="'.$messageid.'" />';
	print '<p align="right"><input type="submit" name="ac" value="'. getTerm('messaging', 'report_message') .'" />';
	print '</div>';
	print '</form>';

    printFooter();
}
elseif ( $action=='write' )
{
	pushNavigationItem( getTerm('messaging', 'messaging'), '/messaging/' );
	
	if ( $draftid==0 )	
	{
		$username = param('username');
		pushNavigationItem( getTerm('messaging', 'send_a_message'), '/messaging/write/' );
	}
	else
	{
		pushNavigationItem( getTerm('messaging', 'drafts'), '/messaging/drafts/' );
		pushNavigationItem( fill( getTerm('messaging', 'send_modify_draft'), $username ) , '/messaging/drafts/' );
	}
	
	printHeader( getTerm('base', 'site_name') , fill( getTerm('messaging', 'send_message_to'), $username ), 'messaging' );

	print "<form action=\"${_SERVER[REQUEST_URI]}\" method=\"post\">";

	if ( $draftid>0 )
		print '<input type="hidden" name="did" value="'. $draftid .'" />';

	print "<div class=\"field". (empty($usernameerror) ? '' : ' error') ."\"><label for=\"username\">" . getTerm('messaging', 'to') . "</label>";
	print (empty($usernameerror) ? '' : "<div class=\"error-hint\">$usernameerror</div>");
	print "<input type=\"text\" id=\"username\" name=\"username\" value=\"$username\" />";
	print "</div>";
	
	print "<div class=\"field". (empty($subjecterror) ? '' : ' error') ."\"><label for=\"subject\">" . getTerm('messaging', 'subject') . "</label>";
	print (empty($subjecterror) ? '' : "<div class=\"error-hint\">$subjecterror</div>");
	print "<input type=\"text\" id=\"subject\" name=\"subject\" value=\"$subject\" />";
	print "</div>";
	
	print "<div class=\"field". (empty($messageerror) ? '' : ' error') ."\"><label for=\"message\">" . getTerm('messaging', 'your_message') . "</label>";
	print (empty($messageerror) ? '' : "<div class=\"error-hint\">$messageerror</div>");
	print "<textarea id=\"message\" name=\"message\">". $message ."</textarea>";
	print "</div>";
		
	print '<div class="field"><input type="submit" name="ac" value="' . getTerm('messaging', 'send_message') . '" /> <input type="submit" name="ac" value="' . getTerm('messaging', ($draftid==0 ? 'save_as_draft' : 'save_draft') ) . '" />';
	
	if ( $draftid>0 )
		print ' <input type="submit" name="ac" value="'. getTerm('messaging', 'delete_draft') .'" />';
	print '<br>';

	list($left, $limit) = check_messages($userid);

	$limit_message = fill(getTerm('messaging', 'limit_state'), $left, $limit);
	echo "<br>$limit_message";

	print '</div>';
	
	print "</form>";
	
	printFooter();
}
elseif ( $action=='send' )
{
	redirect('..');
}
else
{
	$currentFolder = array_key_exists('folder', $_GET) ? $_GET['folder'] : 'inbox';
	
	pushNavigationItem( getTerm('messaging', 'messaging'), '/messaging/' );
	
	$sentflag = 0;
	
	if ( $currentFolder=='inbox' )
	{
		$sql = "SELECT m.id,subject,date,username
				FROM message m
				JOIN user s ON m.from=s.id
				WHERE m.to='$userid'
				AND m.visibleby='$userid'
				AND m.draftflag=0
				ORDER BY date DESC;";
				
		$sentflag = 0;
	}
	elseif ( $currentFolder=='sent' )
	{
		pushNavigationItem( getTerm('messaging', 'sent_items'), '/messaging/sent/' );
		
		$sql = "SELECT m.id,subject,date,m.toname AS 'username'
				FROM message m
				WHERE m.from='$userid'
				AND m.visibleby='$userid'
				AND m.draftflag=0
				ORDER BY date DESC;";
				
		$sentflag = 1;
	}
	elseif ( $currentFolder=='drafts' )
	{
		pushNavigationItem( getTerm('messaging', 'drafts'), '/messaging/drafts/' );
		
		$sql = "SELECT m.id,m.subject,m.date,m.toname AS 'username'
				FROM message m
				WHERE m.from='$userid'
				AND m.visibleby='$userid'
				AND m.draftflag=1
				ORDER BY date DESC;";
				
		$sentflag = 1;
	}
	
	printHeader( getTerm('base', 'site_name') , getTerm('messaging', 'messaging'), 'messaging' );

	if ( ! empty($_SESSION['message']) )
	{
		print "<div class=\"information\">". $_SESSION['message'] ."</div>";
		$_SESSION['message'] = '';
	}
	
	$folders = array();
	$folders['inbox'] = '';
	$folders['sent'] = 'sent';
	$folders['drafts'] = 'drafts';
	
	print '<div id="jump" class="box"><p>';
	print '<form action="'. $_SERVER['REQUEST_URI'] .'" method="post">';
	print '<label for="toFolder">'. getTerm('messaging','go_to') .'</label>';
	print '<input type="hidden" name="ac" value="goto" />';
	print '<select name="toFolder" id="toFolder">';
	foreach ($folders as $label => $folder)
		print '<option value="'. $folder .'"'. ($currentFolder==$folder ? ' selected="selected"' : '') .'>'. getTerm('messaging',$label) .'</option>';
	print '</select>';
	print '<input type="submit" value="'. getTerm('messaging','go') .'" />';
	print '</form>';
	print '</p></div>';
	
	$rh = query($sql);
	
	print '<div id="messages" class="box">';
	print '<form action="'. $_SERVER['REQUEST_URI'] .'" method="post">';
	print '<table>';
	print '<tr><th class="selection-col"></th><th class="subject-col">'. getTerm('messaging','subject') .'</th><th class="sender-col">'. getTerm('messaging', ($sentflag ? 'to' : 'from')) .'</th><th class="date-col">'. getTerm('messaging','date') .'</th></tr>';
	
	if ( mysql_num_rows($rh)!=0 )
	{
	
		while ( $message = mysql_fetch_assoc($rh) )
		{
			$username = '<a href="'. formatUrl('/profile/'. $message['username']) .'">'. $message['username'] .'</a>';
			$subject = '<a href="'. formatUrl('/messaging/message-'. $message['id'] .'.html') .'">'. $message['subject'] .'</a>';
			$date = formatDate($message['date']);
			$time = formatTime($message['date']);
			$mid = $message['id'];
			
			print "<tr><td><input type=\"checkbox\" name=\"selection[]\" value=\"$mid\" /></td><td>$subject</td><td>$username</td><td>$date, $time</td></tr>";
			
		}
	
		print '</ul></li>';
	
	}
	else
	{
		print '<tr><td colspan="4"><p class="no-message">'. getTerm('messaging','no_message_in_folder') .'</p></td></tr>';
	}
	
	print '<tr><td colspan="4" class="action-row"><input type="submit" name="ac" value="'. getTerm('messaging', ($currentFolder=='drafts' ? 'delete_selected_drafts' : 'delete_selected_messages') ) .'" /></tr>';
	print '</table>';
	print '</form>';
	print '</div>';

	printFooter();
}



function check_messages($userid) {

$premium_limit = 100;
$limited_countries = array(
	100, #india
	163, #pakistan
);

$messages_common = array(5, 10, 20);
$messages_limited = array(2, 3, 5);

$time_limits = array(3, 12, 9999);

	$values = $messages_common;

	$rh = query("SELECT country FROM profile WHERE user=$userid AND valid IS NOT NULL;");
	
	if (mysql_num_rows($rh) > 0 ) {
		list($country) = mysql_fetch_array($rh);

		if (in_array($country, $limited_countries)) {
			$values = $messages_limited;
		}
	}
	$limits = array_combine($time_limits, $values);

	$rh = query("SELECT premium,TIMESTAMPDIFF(DAY, since, NOW()) from `user` WHERE id=$userid");
	list($premium, $days) = mysql_fetch_array($rh);

	$rh = query("SELECT COUNT(*) FROM `message` WHERE `from` = $userid AND `visibleby` = $userid AND `draftflag` = 0 AND `date` BETWEEN CONCAT(CURDATE(), ' ', '00:00:00') AND CONCAT(CURDATE(), ' ', '23:59:59')");
	list($sent) = mysql_fetch_array($rh);

	$limit = 5;

	if ($premium == 1) {
		$limit = $premium_limit;
	} else {
		foreach ($limits as $months => $val) {
			if ($num < $months) {
				$limit = $val;
				break;
			}
		}
	}

	$left = $limit - $sent;
	return array($left, $limit);
}


?>
